import csv
import sys
import os

filepath = os.getcwd() + '/py_translate.csv'
writeDir = os.getcwd() + '/py_result/'

def trimText(x:str) -> str:
    if len(x) == 0:
        return x

    # 去除前后空格
    charSet = {' ', '\n', '\r', '\t', '\"'}
    idx = 0

    for text in x:
        if text in charSet:
            idx += 1
            continue
        break

    ridx = 0
    length = len(x)
    for index in range(1, length):
        if x[-index] in charSet:
            ridx += 1
            continue
        break
    end = length - ridx
    x = x[idx:end]
    return x

def escapeText(x:str) -> str:
    # 特殊符号转义
    x = x.replace('\\"', '"')
    x = x.replace('"', '\\"')
    return x

def processText(x:str) -> str:
    result = trimText(x)
    result = escapeText(result)
    return result

def peapareFolder(dir):
    if os.path.exists(dir):
        with os.scandir(dir) as scanner:
            for file in scanner:
                os.remove(file.path)
        os.rmdir(dir)    
    os.mkdir(dir)

if __name__ == '__main__':
    translateList = []
    titleRow = None
    with open(filepath, 'r') as file:
        csvReader = csv.reader(file)
        if csvReader is None:
            exit()

        titleRow = next(csvReader)
        titleColumnCount = len(titleRow)

        # 输入开始列
        hint = ''
        index = 0
        for text in titleRow:
            index += 1
            hint += str(index)
            hint += '.'
            hint += text
            if index < titleColumnCount:
                hint += ', '
        hint += '\n'

        inputMainKey = input('input start column: ' + hint)
        if len(inputMainKey) == 0:
            exit()
        inputMainKeyIndex = int(inputMainKey) - 1
        if inputMainKeyIndex < 0 or inputMainKeyIndex > titleColumnCount:
            exit()
        print('start column is: ' + titleRow[inputMainKeyIndex])

        for i in range(inputMainKeyIndex + 1, titleColumnCount):
            translateList.append([])

        #读csv文件获取数据
        for row in csvReader:
            for column in range(inputMainKeyIndex+1, titleColumnCount):
                originText = row[inputMainKeyIndex]
                transText = row[column]
                
                originText = processText(originText)
                transText = processText(transText)

                transListIndex = column - inputMainKeyIndex - 1
                curTranList = translateList[transListIndex]
                text = '\"'+originText+'\"'+' = '+'\"'+ transText +'\"'+';'+'\n'
                curTranList.append(text)
        
        # 准备文件夹
        peapareFolder(writeDir)

        # 写入文件
        index = inputMainKeyIndex + 1
        for curTranList in translateList:
            name = titleRow[index]
            index += 1
            writePath = writeDir + name + '.strings'
            print('写入:' + name)
            with open(writePath, 'w') as file:
                file.writelines(curTranList)
